package apacheshiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import apacheshiro.model.User;
import org.springframework.util.StringUtils;

public class CustomRealm extends AuthorizingRealm {

    @Override //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = principalCollection.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //根据userName去找用户，以下是不连接数据库的伪操作
        String[] roles = {"admin","create","delete"};Set<String> sroles = new HashSet<String>();sroles.addAll(Arrays.asList(roles)); //设置用户角色
        //以上表示从数据库根据userName找用户
        simpleAuthorizationInfo.setRoles(sroles);
        String[] permit = {"create","modify","delete"};Set<String> spermit = new HashSet<String>();spermit.addAll(Arrays.asList(permit)); //设置用户权限
        simpleAuthorizationInfo.setStringPermissions(spermit);
        return simpleAuthorizationInfo;
    }

    @Override   //登录
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = authenticationToken.getPrincipal().toString();
        System.out.println(userName);

        User user = new User();
        user.setName(userName);
        //数据库伪操作，根据userName查找用户
        if (!"abc".equals(userName) )
        {
            //为找到用户，UnknownAccountException异常
            return null;
        }
        //找到用户，返回authenticationInfo，shiro会与提交的数据做比对，密码错误IncorrectCredentialsException异常
        //user.getPassword()为空，AuthenticationException异常
        user = new User();user.setName(userName);user.setPassword("123");user.setUid(2L);user.setCtime(new Date());
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), "peng");
        return authenticationInfo;
    }
}
